"""
千帆大模型
QIANFAN_ACCESS_KEY: ALTAKVMW05mav4NilQNwpHDlSl
Secret Key: 0030dc450f60423caeef2b1d390a9572

目标要求：
    1. 安装程序
    2. 自动打开微信，自动聊天，包括打开聊天窗口，输入信息，发送，最好能获取到别人发的内容是什么（也可以找个免费的 AI，
    把别人发的信息做一层转发，实现自动回复）
    3. 尝试：定时打开微信，对所有未读信息进行自动回复
"""
import queue
import threading
import time


from MyPackage import AIModel as ai, AutoReplyUtils as util
from MyPackage.MessageThread import MessageThread as mt

import uiautomator2 as u2
from MyPackage.Constant import App

"""
微信自动回复
1. 建立设备连接
2. 启动应用程序
3. 获取当前是否接收新消息：
    3.1 True:
        3.1.1 获取总信息数
        3.1.2 获取当前屏幕页待回复元素
        3.1.3 迭代元素,获取当前元素已接收信息数,拉取该信息(需考虑当前屏幕页信息数量<当前元素已接收信息数)
        3.1.4 调取Ai对话模型接收响应结果
        3.1.5 由于微信回复限长,对响应结果进行切片操作，依次回复
        3.1.6 返回微信导航主页
4. 关闭App
"""


class MyThread:
    def __init__(self):
        self.message_queue = queue.Queue()  # 消息队列
        self.last_msg = ['', '微信', '通讯录', '发现', '我']
        self.running = True

    def start_message_listener(self, window):
        def message_listener():
            while self.running:
                try:
                    el = window(className='android.widget.TextView')[-1]
                    if el.info['bounds']['right'] <= 1048 and el.info['bounds']['bottom'] == 2559:
                        try:

                            if (util.get_text(el) not in self.last_msg
                                    and (self.message_queue.qsize() <= 5)
                                    and '[AI回复]: ' not in util.get_text(el)):
                                self.last_msg[0] = util.get_text(el)
                                self.message_queue.put(util.get_text(el))
                                print(util.get_text(el))
                        except u2.exceptions.UiObjectNotFoundError as e:
                            continue
                except u2.exceptions.UiObjectNotFoundError:
                    continue

            # while self.running:
            #     els = window(className='android.widget.RelativeLayout', index=1)
            #     e = els[-1]
            #     try:
            #         if e.child(className='android.widget.TextView').info['clickable']:
            #             if (util.get_text(
            #                     e.child(className='android.widget.TextView')) not in self.last_msg
            #                     and (self.message_queue.qsize() <= 5)
            #                     and '[AI回复]: ' not in util.get_text(
            #                         e.child(className='android.widget.TextView'))):
            #                 self.last_msg[0] = util.get_text(e.child(className='android.widget.TextView'))
            #                 self.message_queue.put(util.get_text(e.child(className='android.widget.TextView')))
            #                 print(util.get_text(e.child(className='android.widget.TextView')))
            #                 time.sleep(2)
            #     except Exception as e:
            #         time.sleep(2)
            #         continue

            # 启动消息监听线程

        threading.Thread(target=message_listener, daemon=True).start()

    def get_new_message(self):
        # 从队列中获取新消息
        if not self.message_queue.empty():
            return self.message_queue.get()
        return None

    def get_size(self):
        return self.message_queue.qsize()

    def stop(self):
        self.running = False

    def start_thread(self):
        self.running = True


class AppAutoReply(object):
    def __init__(self, device_ip, app):
        try:
            self.__device = u2.connect(device_ip)
        except Exception as e:
            raise Exception(f'设备连接失败,具体原因: {e}')
        self.__app = app
        self.__package = App[app].value
        self.__message_thread = MyThread()  # 测试

    def __start_app(self):
        try:
            print(self.__package)
            self.__device.app_start(self.__package)
        except Exception as e:
            raise Exception(f'程序启动失败, 具体原因: {e}')

    def __determine_replay(self):
        func_name = '_AppAutoReply__' + self.__app.lower() + '_auto_reply'
        if func_name in AppAutoReply.__dict__:
            method = getattr(self, func_name)
            if callable(method):
                method()

    def __wechat_auto_reply(self):
        while True:
            msg_total_el = self.__device(resourceId='com.tencent.mm:id/osw')
            if len(msg_total_el) != 0:
                msg_total = int(msg_total_el.get_text())
                while msg_total > 0:
                    current_page_els = self.__device(resourceId="com.tencent.mm:id/o_u")
                    if len(current_page_els) > 0:
                        for el in current_page_els:
                            current_msg_num = int(el.get_text())
                            msg_total -= current_msg_num
                            el.click()  # 进入聊天窗口内
                            # 待处理 -- 考虑需要滚屏情况获取信息  聊天窗口内动态获取信息
                            """
                            考虑单开线程, 线程内唯一信息池set,以及set长度, 当set长度发生变化则对方有新信息加入
                            当信息处理完毕时则删除池内已处理信息
                            """

                            # --------------------------------------------测试
                            self.__message_thread.start_thread()
                            self.__message_thread.start_message_listener(self.__device)
                            flag = True
                            time.sleep(2)
                            while flag:
                                new_message = self.__message_thread.get_new_message()
                                if new_message:
                                    self.__ai_reply('ERNIE-4.0-8K', new_message)
                                if self.__message_thread.get_size() == 0:
                                    self.__message_thread.stop()
                                    flag = False
                            # --------------------------------------------测试

                            # --------------------------------------------------已测试
                            # msgs = list(self.__device(className="android.widget.TextView"))
                            # to_msg = ''.join(util.get_text(msg) + '\n' for msg in msgs[-current_msg_num:])
                            # self.__ai_reply('ERNIE-4.0-8K', to_msg)
                            # --------------------------------------------------
                            # 返回导航界面
                            self.__device.press('back')
                        # 获取当前总信息量
                    current_msg_total = self.__device(resourceId="com.tencent.mm:id/osw")
                    if len(current_msg_total) == 0:
                        break
                    else:
                        current_msg_total = int(current_msg_total.get_text())
                        if current_msg_total != msg_total:
                            msg_total = current_msg_total
                            # 滚屏置顶
                            while len(self.__device(resourceId="com.tencent.mm:id/o_u")) <= 0:
                                self.__device.swipe(500, 1500, 500, 1800, 0.3)
                        else:
                            self.__device.swipe(500, 1500, 500, 1100, 0.3)

    def __other_app_ml(self):
        pass

    def __group_reply(self):
        pass

    def __single_replay(self):
        pass

    def __test(self):
        #  单对单回复信息获取
        # self.__device(resourceId="com.tencent.mm:id/o4q").click()
        ai_model = ai.DrawModel()
        self.__device.send_keys(ai_model.reply('cat'))
        # els = self.__device(className='android.widget.TextView')[-1]
        # print(els.info)
        # if els.info['bounds']['right'] <= 1048 and els.info['bounds']['bottom'] == 2559:
        #     print(els.get_text())

    def __ai_reply(self, model_name, message):
        ai_model = ai.AIModel(model_name)
        ai_reply = '[AI回复]: ' + ai_model.replay(message)
        self.__device(resourceId="com.tencent.mm:id/o4q").click()
        self.__device.set_input_ime(True)
        self.__device.send_keys(ai_reply)
        self.__device.set_input_ime(False)
        self.__device.press('back')
        self.__device(resourceId="com.tencent.mm:id/bql").click()
        del ai_model

    def run(self):
        # self.__determine_replay()
        self.__test()


if __name__ == '__main__':
    # c1 = MyThread()
    # app1 = AppAutoReply('192.168.101.9:5555', 'WeChat', c1)
    app1 = AppAutoReply('10.11.246.185:5555', 'WeChat')
    app1.run()
